<!-- 注册 -->
<template>
  <div class="register_bg">
    <div class="register_title">注册</div>
    <van-form @submit="onSubmit">
      <van-cell-group inset class="">
        <van-field
          v-model="userName"
          left-icon="user-o"
          name="userName"
          label="用户名"
          clearable
          placeholder="用户名"
          clickable
          :rules="[
            { required: true, message: '请填写用户名' },
            {
              validator: checkUserName,
              trigger: ['onBlur', 'onChange'],
            },
          ]"
        />
        <van-field
          v-model="userPassword"
          type="password"
          clearable
          left-icon="closed-eye"
          name="userPassword"
          label="密码"
          clickable
          placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <van-field
          v-model="ensurePassword"
          type="password"
          clearable
          left-icon="closed-eye"
          name="ensurePassword"
          label="确认密码"
          clickable
          placeholder="确认密码"
          :rules="[
            { required: true, message: '请再一次输入密码' },
            {
              validator: checkEnsurePassword,
              trigger: ['onBlur', 'onChange'],
            },
          ]"
        />
        <van-field
          v-model="userPhone"
          clearable
          left-icon="phone-circle-o"
          name="userPhone"
          label="手机号"
          clickable
          placeholder="手机号"
          :rules="[
            { required: true, message: '请填写手机号', trigger: 'onBlur' },
            {
              pattern: /^1[3|4|5|7|8][0-9]{9}$/,
              message: '请输入正确的手机号',
              trigger: ['onBlur', 'onChange'],
            },
            {
              validator: checkPhone,
              trigger: ['onBlur', 'onChange'],
            },
          ]"
        />
        <van-field
          v-model="smsCode"
          center
          label="短信验证码"
          placeholder="请输入短信验证码"
          :rules="[
            { required: true, message: '请输入验证码', trigger: 'onBlur' },
            // {
            //   validator: checkVerification,
            //   // message: '验证码错误',
            //   trigger: ['onBlur', 'onChange'],
            // },
          ]"
        >
          <template #button>
            <van-button size="small" type="primary" round @click="clickSendSMS">
              {{ codeBtnText }}&nbsp;{{ downTimeText }}
            </van-button>
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px;">
        <van-button round block type="primary" native-type="submit">
          <span class="login_font_style">注&emsp;&emsp;册</span>
        </van-button>
      </div>
      <div class="haveAccount">
        已注册过，去
        <span style="color: blue;" @click="toLogin">登陆</span>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from 'vant'
import { ref } from 'vue'
import {
  userRegister,
  checkUserNameApi,
  checkPhoneApi,
} from '../../api/register.js'
import {
  getVerificationCodeByPhone,
  // checkVerificationApi,
} from '../../api/music'
export default {
  data() {
    return {
      userName: '',
      userPassword: '',
      userPhone: '',
      ensurePassword: '',
      smsCode: '', // 短信验证码
      downTime: 60, // 倒计时时间
      downTimeText: '', // 点击发送验证码之后显示
      codeBtnText: '发送验证码', // 发送验证码按钮的文字
      isCodeBtnClick: false, // 发送验证码的按钮是否被点击
    }
  },

  setup() {
    const userName = ref('')
    const userPassword = ref('')
    const userPhone = ref('')
    const ensurePassword = ref('')
    // 验证密码是否一致
    const checkEnsurePassword = () => {
      if (userPassword.value !== ensurePassword.value) {
        return '前后密码不一致！'
      }
    }

    // 验证手机号是否重复
    const checkPhone = () => {
      return checkPhoneApi(userPhone.value).then((res) => {
        if (res.data.data) {
          return '该号码已被注册！'
        }
      })
    }

    return {
      userName,
      userPassword,
      ensurePassword,
      userPhone,
      checkEnsurePassword,
      checkPhone,
    }
  },

  methods: {
    // 去登陆
    toLogin() {
      this.$router.push('/login')
    },

    // 验证用户名是否唯一
    checkUserName() {
      return checkUserNameApi(this.userName).then((res) => {
        if (res.data.data) {
          return '该用户名已被注册！'
        }
      })
    },

    // 点击注册
    onSubmit() {
      var params = {
        userName: this.userName,
        userPassword: this.userPassword,
        userPhone: this.userPhone,
        captcha: this.smsCode,
      }
      userRegister(params).then((res) => {
        if (res.data.code === 10000) {
          // 注册成功，跳转登陆
          Toast.success({
            message: res.data.message,
            duration: 1000,
          })
          setTimeout(() => {
            this.$router.push('/login')
          }, 900)
        }else{
          this.$toast.fail(res.data.message)
        }
      })
    },

    // 点击发送验证码
    clickSendSMS() {
      if (this.userPhone != '') {
        var phoneReg = /^1[3-9][0-9]{9}$/
        console.log(phoneReg.test(this.userPhone))
        if (phoneReg.test(this.userPhone)) {
          // 手机号格式正确
          checkPhoneApi(this.userPhone).then((res) => {
            if (res.data.data) {
              this.$toast.fail('该手机号已被注册过,请返回登陆！')
            } else {
              getVerificationCodeByPhone(this.userPhone).then((res) => {
                if (res.data.data) {
                  this.isCodeBtnClick = true
                  this.codeBtnText = '已发送'
                  this.$toast.success('请注意查收网易云音乐验证码！')
                  this.TimeWatch()
                } else {
                  if (res.data.data.code == 400) {
                    this.$toast.fail(res.data.data.message)
                  } else {
                    this.$toast.fail('验证码获取失败，请检查手机号稍后再试！')
                  }
                }
              })
            }
          })
        } else {
          this.$toast.fail('手机号格式不正确！')
        }
      } else {
        this.$toast.fail('手机号不能为空！')
      }
    },

    // 倒计时函数
    TimeWatch() {
      const interval = window.setInterval(() => {
        // downTime值自减
        this.downTime--
        //打印每次递归函数打印time值
        console.log(this.downTime)
        this.downTimeText = this.downTime + 's'
        if (this.downTime == 0) {
          window.clearInterval(interval)
        }
      }, 1000)
    },

    // 检验验证码正确与否
    // checkVerification() {
    //   checkVerificationApi(this.userPhone, this.smsCode)
    //     .then((res) => {
    //       if (res.data.data) {
    //         return ''
    //       } else {
    //         return res.data.data.message
    //       }
    //     })
    //     .catch(() => {
    //       return '验证码错误'
    //     })
    //   return '验证码错误'
    // },
  },
  watch: {
    downTime() {
      if (this.downTime == 0) {
        setTimeout(() => {
          this.isCodeBtnClick = false
          this.downTime = 60
          this.downTimeText = ''
          this.codeBtnText = '发送验证码'
        }, 900)
      }
    },
  },
}
</script>

<style scoped>
.register_bg {
  width: 100%;
  height: 667px;
  background-image: url('https://myblog-mycaveolae.oss-cn-chengdu.aliyuncs.com/bg/mohu_register_bg.jpg');
  background-size: cover;
  background-repeat: no-repeat;
}
.register_title {
  width: 5em;
  margin: auto;
  text-align: center;
  height: 5em;
  font-weight: bold;
  letter-spacing: 8px;
  /* background-color: rgb(74, 78, 81); */
  padding-top: 2em;
  color: aliceblue;
  font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
  font-size: 24px;
}
.van-form {
  opacity: 0.7;
  position: relative;
  top: -50px;
}
.haveAccount {
  width: 100%;
  height: 100px;
  /* background-color: aliceblue; */
  text-align: center;
}
</style>
